package com.xx.springsecuritydemo.main.controller;

import cn.hutool.core.io.FastByteArrayOutputStream;
import com.google.code.kaptcha.Producer;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 验证码controller
 */
@Controller
public class KaptchaController {
    private final Producer producer;

    /**
     * 使用构造函数注入 --- 面相接口编程思想 如需指定顶层实现，可以通过@Qualifier注解指定
     * @param producer
     */
    @Autowired
    public KaptchaController(Producer producer) {
        this.producer = producer;
    }

    /**
     * 前后端不分离获取验证码
     * @param response
     * @param session
     * @throws IOException
     */
    @GetMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {
        response.setContentType("image/png");
        String code = producer.createText();
        System.out.println("验证码:" + code);
        session.setAttribute("kaptcha", code);
        BufferedImage image = producer.createImage(code);
        ServletOutputStream os = response.getOutputStream();
        ImageIO.write(image, "jpg", os);
    }

    /**
     * 前后端分离获取验证码
     * @param response
     * @param session
     * @throws IOException
     */
    @GetMapping("/yz.jpg")
    @ResponseBody
    public String getVerifyCode2(HttpServletResponse response, HttpSession session) throws IOException {
        //1.⽣成验证码
        String code = producer.createText();
        // 可以更换成 redis 实现
        session.setAttribute("kaptcha", code);
        System.out.println("验证码:" + code);
        BufferedImage bi = producer.createImage(code);
        //2.写⼊内存
        FastByteArrayOutputStream fos = new FastByteArrayOutputStream();
        ImageIO.write(bi, "png", fos);
        // 3.⽣成 base64
        return Base64.encodeBase64String(fos.toByteArray());
    }
}
